package event.money.tracker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import MTClient.ClientLogic;
import MTClient.LocalPhoneContactManager;
import MTClient.MTConstant;
import SQLManager.SQLManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;

public class MainContacts extends Activity implements OnItemClickListener {

	/** Called when the activity is first created. */  
	private MultipleChoiceAdapter mSimpleAdapter = null;
	
	private ProgressDialog loadingpopup = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    setContentView(R.layout.main_contacts);
	    
	    // set current activity (need this for callback)
        ClientLogic.SetCurrentActivity(this);
        
	    // sync contacts
	    Log.e( "Money", "Request ID :" + MTConstant.MT_REQID_SYNCHRONIZE_CONTACT_LIST);
		//mClientTCP.SendRequest(MTConstant.MT_REQID_SYNCHRONIZE_CONTACT_LIST );
	    LocalPhoneContactManager.CompareLocalDb(getBaseContext());

	    
	    //LocalPhoneContactManager();
	   
	    //Load new Contact from Local SQLDB;
	    
	   	
	   	//Calling DrawContact UI Method
	   	DrawContact();
	   	
	   	Button addEventButton = (Button)this.findViewById(R.id.AddEvent);
	   	addEventButton.setOnClickListener(new View.OnClickListener() {

        	public void onClick(View view) {
        	    setResult(RESULT_OK);
        	    System.out.println("inAddEvent");
        	    getChecked();
        	    
        	}

        });
	   	
	   	Button syncButton = (Button)this.findViewById(R.id.ContactListSync);
	   	syncButton.setOnClickListener(new View.OnClickListener() {

        	public void onClick(View view) {
        	    setResult(RESULT_OK);
        	    System.out.println("syncing contacts");
        	    
        	    if( ClientLogic.GetInstance().SendSynContactListRequest() ) {
        	    	// popup loading dialog
        	    	loadingpopup = ProgressDialog.show(MainContacts.this, "", 
        	                "Loading. Please wait...", true);
        	    }
        	    
        	}

        });
	}
	
	protected void onStart()
	{
		super.onStart();
	    
	    ClientLogic.SetCurrentActivity(MainContacts.this);
	}
	
	
	public void DrawContact(){
		//////////////////
		//Data Construct
		//////////////////
		
		//Create an ArrayList to Storage the Data
		ArrayList<Map<String, String>> listitems = new ArrayList<Map<String,String>>();
		
		//Loop out all data
		SQLManager.GetInstance().open();
		Cursor ContactListCur = SQLManager.GetInstance().FetchContactList();
		if (ContactListCur.getCount() > 0) {
			while (ContactListCur.moveToNext()) {
				String id = ContactListCur.getString(ContactListCur.getColumnIndex("UserID"));
				String name = ContactListCur.getString(ContactListCur.getColumnIndex("UserName"));
				String phone = ContactListCur.getString(ContactListCur.getColumnIndex("PhoneNumber"));
				System.out.println("Draw-ID:"+id);
				System.out.println("Draw-Name:"+name);
				System.out.println("Draw-Phone:"+phone);
				
				//Adding data into ArrawyList
				Map<String, String> map=new HashMap<String, String>();
				map.put("DrawingID", id);
				map.put("DrawingName", name);
				map.put("DrawingPhone", phone);
				//map.put(I, value);
				if(id != null)
					listitems.add(map);
			}
		}
		
		//////////////////////
		// UI Construct
		//////////////////////
		
		// Instance the ListView
	   	final ListView ContactListView = (ListView)findViewById(R.id.ContactListView01);
	   
	   	String[] from = { MultipleChoiceAdapter.NAME, MultipleChoiceAdapter.PHONE_NUMBER };  
        int[] to = { R.id.ContactNameTV, R.id.ContactPhoneTV };  
	    mSimpleAdapter = new MultipleChoiceAdapter( this, listitems, R.layout.contact_items, from, to );

		
		//////////////////////
		//Interaction Handling
		//////////////////////
		ContactListView.setAdapter(mSimpleAdapter);
		ContactListView.setOnItemClickListener(this); 
		
	}
	
	public void getChecked(){
		ArrayList< Integer > userWithClicked = new ArrayList();
		
		// Filter the user who the checked box is true
		for( int i = 0 ; i < mSimpleAdapter.getCount(); ++i ){
			if( mSimpleAdapter.IsChecked( i ) ){
				userWithClicked.add( Integer.valueOf(i) );
			}
			//mSimpleAdapter.g
			
		}
		
		//ArrayList<Map<String, String>> listitems = new ArrayList<Map<String,String>>();
		//Map<String, String> bundleMap=new HashMap<String, String>();
		//bundleMap.put("ID",id);
		//bundleMap.put("NAME", name);
		//bundleMap.put("PHONE", phone);
		
		//Useback the Intent by phone in next activity/UI
		
		ArrayList<String> selected_phone = new ArrayList<String>();
		//ArrayList<String> selected_list = new ArrayList<String>();
		String name = null;
		//String number = null;
		
		//A intent for next activity EditEvent.java
		Intent intent =new Intent(this, EditEvent.class);
		Bundle b = new Bundle();
		
		for( int i = 0 ; i < userWithClicked.size(); ++i ){
			int position = userWithClicked.get( i ).intValue();
			System.out.println("i:" + i + " Name :" + mSimpleAdapter.GetName( position ));
			System.out.println("i:" + i + " PhoneNum :" + mSimpleAdapter.GetPhoneNum( position ));
			System.out.println("i:" + i + " isChecked :" + mSimpleAdapter.IsChecked( position ));
			
			//name = mSimpleAdapter.GetName( position ).toString();
			//bundleMap.put("NAME", name);
			//selected_phone.add(name);
			name = mSimpleAdapter.GetPhoneNum( position ).toString();
			//bundleMap.put("NUMBER", number);
			selected_phone.add(name);
			
			//b.putStringArray(selected_list, new String[]{name, number});
		}
		b.putStringArrayList("flying_list", selected_phone);
		intent.putExtras(b);
		//Passing the data in ACTIVITY_CREATE mode
		startActivityForResult(intent, 0);
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		CheckBox checkBox = (CheckBox) view.findViewById(R.id.ContactCheckBox);  
        
        checkBox.toggle();  
          
        mSimpleAdapter.map.put(position, checkBox.isChecked());  
        
        System.out.println( "Checked Tap! ");
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //Redraw the Contacts after back
        DrawContact();
        
        if(resultCode == 5) // event created, set event tab
        	((MainTabView)this.getParent()).setTab(0);
    }
	
		public void handle_update_result(boolean success) {
    	
	    	loadingpopup.dismiss();
	    	
	    	// Redraw the Contacts after update in UI thread
	    	
	        this.runOnUiThread(new Runnable() {
    		    public void run() {
    		    	MainContacts.this.DrawContact();
    		    }
    		});
    		
		}
	

}
